<template>
  <div class="goods_container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 输入搜索以及点击添加 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="goodsParams.query" clearable>
            <el-button slot="append" icon="el-icon-search" @click="inputSearch"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="showAddDialog">添加商品</el-button>
        </el-col>
      </el-row>
      <!-- 商品列表 -->
      <el-table :data="goodsList" style="width: 100%; height: 520px" border stripe>
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column prop="goods_name" label="商品名称" width="750"></el-table-column>
        <el-table-column prop="goods_price" label="商品价格" width="150"></el-table-column>
        <el-table-column prop="goods_weight" label="商品重量" width="150"></el-table-column>
        <el-table-column prop="add_time" label="创建时间">
          <!-- 在table中使用过滤器 -->
          <template scope="scope">{{scope.row.add_time|dateFormat}}</template>
        </el-table-column>
        <!-- 使用作用域插槽 -->
        <el-table-column prop="mg_state" label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-tooltip class="item" effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="editGood(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="deleteGood(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="goodsParams.pagenum"
        :page-sizes="[8]"
        :page-size="goodsParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 点击添加商品 -->
    <el-dialog
      title="添加商品"
      :visible.sync="dialogFormVisible"
      width="30%"
      :show-close="false"
      :modal="true"
      :close-on-click-modal="false"
    >
      <el-form :model="newGood" :rules="newGoodRules" ref="newGoodFormRef">
        <el-form-item label="商品名称" label-width="20%" prop="goods_name">
          <el-input v-model="newGood.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" label-width="20%" prop="goods_price">
          <el-input v-model="newGood.goods_price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" label-width="20%" prop="goods_number">
          <el-input v-model="newGood.goods_number" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" label-width="20%" prop="goods_weight">
          <el-input v-model="newGood.goods_weight" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品介绍" label-width="20%">
          <el-input v-model="newGood.goods_introduce" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="选择商品分类">
          <!-- options指定数据源，props指定配置对象label、children是哪个 -->
          <el-cascader
            v-model="cascaderVal"
            :options="parentCateList"
            expandTrigger="hover"
            :props="props"
            @change="handleCascaderChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addGoodCancel">取 消</el-button>
        <el-button type="primary" @click="admitNewGood">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品列表
      goodsList: [],
      // 商品列表查询参数
      goodsParams: {
        query: '',
        pagenum: 1,
        pagesize: 8
      },
      total: 0,
      newGood: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: 1,
        goods_introduce: '',
        goods_cat: [],
        id: '',
        attrs: []
      },
      dialogFormVisible: false,
      newGoodRules: {
        goods_name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        goods_price: [{ required: true, message: '不能为空', trigger: 'blur' }],
        goods_number: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        goods_weight: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      // 设置级联选择器属性
      props: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 级联选择器数据
      parentCateList: [],
      // 编辑或者添加的flag
      flag: '',
      cascaderVal: []
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    async getGoodsList() {
      const { data: res } = await this.$http.get(`goods`, {
        params: this.goodsParams
      })
      console.log(res.data)
      if (res.meta.status != 200) {
        return this.$message.error('获取页面数据失败')
      }
      this.goodsList = res.data.goods
      this.total = res.data.total
    },
    // 监听页码的改变
    handleCurrentChange(val) {
      this.goodsParams.pagenum = val
      this.getGoodsList()
    },
    // 监听每页展示商品数量的改变
    handleSizeChange() {},
    // 编辑商品
    editGood(data) {
      this.flag = 'edit'
      // console.log(data)
      this.newGood = data
      this.dialogFormVisible = true
      this.getParentCateList()
    },
    // 删除商品
    async deleteGood(data) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async _ => {
        const { data: res } = await this.$http.delete(`goods/${data.goods_id}`)
        if (res.meta.status != 200) {
          return this.$message.error('操作失败')
        }
        this.$message.success('操作成功')
        this.getGoodsList()
      })
    },
    inputSearch() {
      this.goodsParams.pagenum = 1
      this.getGoodsList()
    },
    addGoodCancel() {
      this.$refs.newGoodFormRef.resetFields()
      this.dialogFormVisible = false
    },
    // 点击添加商品
    showAddDialog() {
      // this.dialogFormVisible = true
      // this.getParentCateList()
      // this.flag = 'add'
      this.$router.push('/addGoods')
    },
    // 提交新商品
    async admitNewGood() {
      this.$refs.newGoodFormRef.validate(valid => {
        if (!valid) {
          this.$message.closeAll()
          return this.$message.error('请检查输入')
        }
      })
      if (this.cascaderVal === 0) {
        this.$message.closeAll()
        return this.$message.error('请选择分类')
      }
      this.newGood.goods_cat = this.cascaderVal.join()
      console.log(this.newGood)
      // 添加商品操作
      if (this.flag == 'add') {
        const { data: res } = await this.$http.post(`goods`, this.newGood)
        if (res.meta.status != 201) {
          return this.$message.error('操作失败')
        }
        this.$message.success('操作成功')
        this.getGoodsList()
      }
      // 编辑操作
      if (this.flag == 'edit') {
        const { data: res } = await this.$http.put(
          `goods/${this.newGood.goods_id}`,
          this.newGood
        )
        if (res.meta.status != 200) {
          return this.$message.error('操作失败')
        }
        this.$message.success('操作成功')
        this.getGoodsList()
      }
    },
    // 级联选择器变化
    handleCascaderChange() {
      console.log(this.newGood.goods_cat)
    },
    async getParentCateList() {
      // 传递参数需要params
      this.$http.get('categories').then(res => {
        if (res.data.meta.status != 200) {
          return this.$message.error('获取数据失败')
        }
        this.parentCateList = res.data.data
        console.log(this.parentCateList)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.goods_container {
  .el-card {
    margin-top: 20px;
    > .inputSearch {
      width: 250px;
    }
  }
}
</style>